<template>
	<div ref="echartsRef" :class="isCard ? 'card' : ''" :style="{ height }"></div>
</template>

<script setup lang="ts" name="pieChart">
import { ref, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { useEcharts } from '@/hooks/useEcharts';
type Echarts = {
	series: any;
	width?: number | string;
	height?: number | string;
	legend?: any; // 饼图底部显示
	isCard?: true; // 是否有边框
};
const prop = withDefaults(defineProps<Echarts>(), {
	legend: {
		show: true,
		left: 'center',
		top: 'bottom',
		textStyle: {
			color: '#a1a1a1'
		}
	},
	height: '322px'
});
const echartsRef = ref<HTMLElement>();
interface ModelEmits {
	(e: 'pieMouseover', value: number): void;
	(e: 'pieMouseout'): void;
}
const emit = defineEmits<ModelEmits>();

watch(
	() => prop.series,
	() => {
		nextTick(() => {
			initEcharts();
		});
	},
	{ immediate: true, deep: true }
);

const initEcharts = () => {
	const myChart: echarts.ECharts = echarts.init(echartsRef.value as HTMLElement);
	const option: echarts.EChartsOption = {
		tooltip: {
			trigger: 'item',
			formatter: '{a} <br/>{b} : {c} ({d}%)'
		},
		legend: prop.legend,
		toolbox: {
			show: false,
			feature: {
				mark: { show: false },
				dataView: { show: true, readOnly: false },
				restore: { show: true },
				saveAsImage: { show: true }
			}
		},
		series: prop.series
	};

	myChart.on('mouseover', params => {
		const dataIndex = params?.dataIndex;
		emit('pieMouseover', dataIndex);
	});

	myChart.on('mouseout', () => {
		emit('pieMouseout');
	});
	useEcharts(myChart, option);
};
</script>

<style scoped lang="scss"></style>
